import React, { Component } from 'react'
import {
  Form,
  Input,
  Tooltip,
  Icon,
  Checkbox,
  Button,
  Upload,
  message,
  Modal
} from 'antd'
import './index.less'
import { register } from '../../requests/user'
import $ from 'jquery'
@Form.create({ name: 'register' })
export default class Register extends Component {
  constructor() {
    super()
    this.state = {
      confirmDirty: false,
      imageUrl: '',
      loading: false,
      failMeaasge: ''
    }
  }
  //注册按钮
  handleSubmit = e => {
    e.preventDefault()
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.agreement === true
          ? register({
              ...values,
              imageUrl: this.state.imageUrl
            }).then(resp => {
              console.log(resp)
              if (resp.data.data.status === 1) {
                message.success('注册成功')
                this.props.history.push('/login')
              } else if (resp.data.data.message === '该邮箱已被注册') {
                message.error('该邮箱已被注册!')
                $('#register_email').val('')
              } else if (resp.data.data.message === '该用户名已被注册') {
                message.error('该用户名已被注册!')
                $('#register_userName').val('')
              }
            })
          : message.error('请先阅读读书协议并同意')
        // console.log('Received values of form: ', values)
      }
    })
  }

  //密码确认
  handleConfirmBlur = e => {
    const value = e.target.value
    this.setState({ confirmDirty: this.state.confirmDirty || !!value })
  }
  compareToFirstPassword = (rule, value, callback) => {
    const form = this.props.form
    if (value && value !== form.getFieldValue('password')) {
      callback('两次密码不一致,请重新输入!')
    } else {
      callback()
    }
  }
  //输入密码
  validateToNextPassword = (rule, value, callback) => {
    const form = this.props.form
    if (value && this.state.confirmDirty) {
      form.validateFields(['confirm'], { force: true })
    }
    callback()
  }
  //上传头像
  getBase64 = (img, callback) => {
    const reader = new FileReader()
    reader.addEventListener('load', () => callback(reader.result))
    reader.readAsDataURL(img)
  }
  handleChange = info => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true })
      return
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      this.getBase64(info.file.originFileObj, imageUrl =>
        this.setState({
          imageUrl,
          loading: false
        })
      )
    }
  }
  beforeUpload = file => {
    const isJPG = file.type === 'image/jpeg'
    if (!isJPG) {
      message.error('目前只支持 JPG 格式的图片!')
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('图片必须小于 2MB!')
    }
    return isJPG && isLt2M
  }

  //显示换书协议页面
  showModal = () => {
    this.setState({
      visible: true
    })
  }
  //同意换书协议
  handleOk = e => {
    console.log(e)
    this.setState({
      visible: false,
      dealChecked: true
    })
  }
  //拒绝换书协议
  handleAgreementCancel = e => {
    console.log(e)
    this.setState({
      visible: false,
      dealChecked: false
    })
  }

  //跳转到登录页
  toLogin = () => {
    this.props.history.push('/login')
  }
  render() {
    const { getFieldDecorator } = this.props.form

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    }
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0
        },
        sm: {
          span: 16,
          offset: 8
        }
      }
    }
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
    )
    const imageUrl = this.state.imageUrl
    return (
      <div className="register-bg">
        <Form
          {...formItemLayout}
          onSubmit={this.handleSubmit}
          className="register-from"
        >
          <Form.Item label="E-mail">
            {getFieldDecorator('email', {
              rules: [
                {
                  type: 'email',
                  message: '邮箱格式不正确!'
                },
                {
                  required: true,
                  message: '请输入邮箱!'
                }
              ]
            })(<Input />)}
          </Form.Item>
          <Form.Item label="密码" hasFeedback>
            {getFieldDecorator('password', {
              rules: [
                {
                  required: true,
                  message: '请输入密码!'
                },
                {
                  validator: this.validateToNextPassword
                },
                {
                  min: 10,
                  max: 16,
                  pattern: '^(?:[a-zA-Z0-9]+|[!@#$%^&*])$',
                  message: '请输入10~16位数字+字母+!@#$%^&*的密码',
                  required: true
                }
              ]
            })(<Input.Password />)}
          </Form.Item>
          <Form.Item label="密码确认" hasFeedback>
            {getFieldDecorator('confirm', {
              rules: [
                {
                  required: true,
                  message: '请确认密码!'
                },
                {
                  validator: this.compareToFirstPassword
                }
              ]
            })(<Input.Password onBlur={this.handleConfirmBlur} />)}
          </Form.Item>
          <Form.Item
            label={
              <span>
                用户名&nbsp;
                <Tooltip title="此昵称将成为您的展示名称">
                  <Icon type="question-circle-o" />
                </Tooltip>
              </span>
            }
          >
            {getFieldDecorator('userName', {
              rules: [
                {
                  min: 1,
                  max: 16,
                  message: '请输入1~16位任意字符',
                  required: true
                }
              ]
            })(<Input />)}
          </Form.Item>
          <Form.Item label="头像">
            <Upload
              name="avatar"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
              beforeUpload={this.beforeUpload}
              onChange={this.handleChange}
            >
              {imageUrl ? <img src={imageUrl} alt="avatar" /> : uploadButton}
            </Upload>
          </Form.Item>
          <Form.Item {...tailFormItemLayout}>
            {getFieldDecorator('agreement', {
              valuePropName: 'checked',
              initialValue: this.state.dealChecked
            })(
              <Checkbox>
                我已经阅读{' '}
                <a href="###" onClick={this.showModal}>
                  换书协议
                </a>
              </Checkbox>
            )}
          </Form.Item>
          <Form.Item {...tailFormItemLayout}>
            <Button type="primary" htmlType="submit">
              注册
            </Button>
          </Form.Item>
          <Form.Item className="toLogin">
            <p onClick={this.toLogin}>已有账号,返回登录</p>
          </Form.Item>
        </Form>
        <Modal
          title="书籍交换协议"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleAgreementCancel}
          cancelText={'不同意'}
          okText={'同意'}
        >
          <p>Some contents...</p>
          <p>Some contents...</p>
          <p>Some contents...</p>
        </Modal>
      </div>
    )
  }
}
